<!--
 * @Author: 王坤
 * @LastEditors: 王坤
 * @Description: Excel导入
-->
<template>
  <div class="lc-excel-import">
    <el-button v-bind="$attrs" :loading="isShowLoading" @click="handleOpenDialog">
      <template v-if="iconPosition === 'right'">
        {{ label }}
      </template>
      <i v-if="isShowIcon" :style="iconPosition === 'right' ? 'margin-left: 4px' : 'margin-right: 4px'">
        <slot></slot>
      </i>
      <template v-if="iconPosition === 'left'">
        {{ label }}
      </template>
    </el-button>

    <el-dialog
      title="上传数据"
      class="lc-excel-import__dialog"
      width="50%"
      append-to-body
      v-model="isShowDialog"
      :modal="true"
      :before-close="handleCloseDialog"
      :close-on-click-modal="false"
    >
      <div class="lc-excel-import__dialog-header">
        <div class="header-piece"></div>
        <span class="header-label">正常数据</span>
        <el-upload
          multiple
          :action="uploadFileAction"
          :accept="uploadFileAccept"
          :auto-upload="false"
          :show-file-list="false"
          :file-list="uploadFileList"
          :on-change="onChangeUploadFile"
        >
          <el-button class="header-btn">导入数据</el-button>
        </el-upload>
        <el-button class="header-btn" @click="handleDownLoadTemplate">下载模板</el-button>
      </div>
      <el-table class="lc-excel-import__dialog-table" :data="dataList" stripe style="width: 100%">
        <el-table-column prop="isSuccess" label="导入状态">
          <template v-slot="scope">
            <span
              :class="{
                'import-success': scope.row.isSuccess,
                'import-error': !scope.row.isSuccess
              }"
            >
              {{ scope.row.isSuccess ? '成功' : '失败' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="col in headList"
          :key="col.fieldName"
          :prop="col.fieldName"
          :label="col.value"
          :show-overflow-tooltip="true"
        >
          <template v-slot="scope">
            <span
              :class="{
                'import-success': scope.row.isSuccess,
                'import-error': !scope.row.isSuccess
              }"
            >
              {{ scope.row[col.fieldName] }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div>
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { request } from '@/apis/request';
import { downloadFile } from '@/utils/common';
const props = defineProps({
  label: {
    type: String,
    default: ''
  },
  isShowIcon: {
    type: Boolean,
    default: true
  },
  iconPosition: {
    type: String,
    default: 'left'
  },
  isShowLoading: {
    type: Boolean,
    default: false
  },
  uploadUrl: {
    type: String,
    default: ''
  },
  downloadUrl: {
    type: String,
    default: ''
  },
  connectors: {
    type: Object,
    default: () => ({
      downloadErrorDataByApi: {
        queryParams: {},
        resDataName: ''
      },
      downloadFile: {
        queryParams: {},
        resDataName: ''
      },
      parseFile: {
        queryParams: {},
        resDataName: ''
      }
    })
  }
});
const dataList = ref([]);
const headList = ref([]);
const uploadFileList = ref([]);
const isShowDialog = ref(false);
const currentFile = ref(null);
const uploadFileAction = ref('');
const uploadFileAccept = '.xls,.xlsx';

function handleOpenDialog() {
  isShowDialog.value = true;
}
function handleCloseDialog() {
  isShowDialog.value = false;
}
function handleDownLoadTemplate() {
  const { queryParams, resDataName } = props.connectors['downloadFile'];
  request({
    ...queryParams
  })
    .then((res) => {
      downloadFile(resDataName ? res[resDataName] : res);
    })
    .catch((res) => {});
}
function onChangeUploadFile(file) {
  currentFile.value = file;
  const { queryParams, resDataName } = props.connectors['parseFile'];
  const formData = new FormData();
  formData.append('file', currentFile.value.raw);
  request({
    ...queryParams,
    data: formData
  })
    .then((res) => {
      const data = resDataName ? res[resDataName] : res;
      const { dataList, errorList, headList } = data;
      headList.value = headList;
      dataList.value = [
        ...errorList.map((item) => {
          item.isSuccess = false;
          return item;
        }),
        ...dataList.map((item) => {
          item.isSuccess = true;
          return item;
        })
      ];
    })
    .catch((res) => {});
}
function handleSubmit() {
  const { queryParams } = props.connectors['uploadFile'];
  const formData = new FormData();
  formData.append('file', currentFile.value.raw);
  request({
    ...queryParams,
    data: formData
  })
    .then((res) => {
      if (res.success) {
        ElMessage.success({ label: '提示', message: '提交成功' });
      }
    })
    .catch((res) => {});
}
</script>
